package com.emns.service.yuedu;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.emns.dao.LanmuZiyuanMapper;
import com.emns.dao.YueduMapper;
import com.emns.pojo.LanmuZiyuan;
import com.emns.pojo.Yuedu;
import common.DateUtils;
import common.PageInfo;

@Service
public class YueduService {

	@Autowired
	YueduMapper ydm;
	@Autowired
	LanmuZiyuanMapper lzm;

	public void queryPageAll(String keyWord, String startDate, String endDate,
			PageInfo<Yuedu> pageInfo) {
		Date sDate = null;
		Date eDate = null;
		if (keyWord != null && !"".equals(keyWord))
			keyWord = "%" + keyWord + "%";
		else
			keyWord = null;
		if ((startDate != null && !"".equals(startDate))
				&& (endDate != null && !"".equals(endDate))) {
			startDate = startDate + " 00:00:00";
			sDate = DateUtils.parseDate(startDate, "yyyy-MM-dd HH:mm:ss");
			endDate = endDate + " 23:59:59";
			eDate = DateUtils.parseDate(endDate, "yyyy-MM-dd HH:mm:ss");
		} else {
			startDate = null;
			endDate = null;
		}
		List<Yuedu> yuduList = ydm.getRecordPage(keyWord, sDate, eDate,
				pageInfo);
		int count = ydm.getRecordCount(keyWord, sDate, eDate);
		pageInfo.setDataArray(yuduList);
		pageInfo.setPageCount(count);
	}

	// 添加悦读数据
	@Transactional
	public void add(Yuedu yuedu, int flanmu, int[] lanmu) throws Exception {
		ydm.insert(yuedu);
		for (int i = 0; i < lanmu.length; i++) {
			LanmuZiyuan lmzy = new LanmuZiyuan();
			lmzy.setFirstLanmuId(flanmu);
			lmzy.setSecondLanmuId(lanmu[i]);
			lmzy.setZiyuanId(yuedu.getYueduId());
			lmzy.setFlag("1");
			lzm.insert(lmzy);
		}
	}

	// 更新悦读数据
	@Transactional
	public void update(Yuedu yuedu, int flanmu, int[] lanmu) {
		ydm.updateByPrimaryKeySelective(yuedu);
		lzm.deleteByPrimaryKey(yuedu.getYueduId());
		for (int i = 0; i < lanmu.length; i++) {
			LanmuZiyuan lmzy = new LanmuZiyuan();
			lmzy.setFirstLanmuId(flanmu);
			lmzy.setSecondLanmuId(lanmu[i]);
			lmzy.setZiyuanId(yuedu.getYueduId());
			lmzy.setFlag("1");
			lzm.insert(lmzy);
		}
	}

	// 删除悦读数据
	public void delete(Integer[] ids) {
		for (Integer id : ids) {
			if (id != null) {
				Yuedu yuedu = new Yuedu();
				yuedu.setYueduId(id);
				yuedu.setState(1);
				ydm.updateByPrimaryKeySelective(yuedu);
			}

		}
	}

	// 根据阅读编号获取阅读信息
	public Yuedu getYueduById(Integer id) {
		return ydm.selectByPrimaryKey(id);
	}

	public Map<Integer, Boolean> getLanmuZiyuanById(Integer id) {
		Map<Integer, Boolean> map = new HashMap<Integer, Boolean>();
		for (LanmuZiyuan zy : lzm.selectByZid(id)) {
			map.put(zy.getSecondLanmuId(), true);
		}
		return map;
	}
}
